package au.edu.unsw.editingtool.web;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import au.edu.unsw.editingtool.db.DBEditingpool;
import au.edu.unsw.editingtool.db.DBSession;
import au.edu.unsw.editingtool.global.GlobalConstant;

/**
 * @author h.sidhunata 
 * LogoutManager clear some session data and logout user
 * 
 */

public class LogoutManager extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String ServletContext = null;	
	private String ApplicationContext = null;	
	private String ApplicationPath = null;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogoutManager() {
    	super();    	        
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doGet(request, response);
		this.doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(request, response);
		this.doService(request, response);
	}

	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		ServletContext = getServletContext().getRealPath("") + GlobalConstant.fileSeparator;
		System.out.println("==== [LOGOUTMANAGER Servlet] ====");
		HttpSession session = request.getSession();
		
		String querystring = request.getQueryString();
		
		// TODO
		// 1. Clean session table with the username found.
		// 2. Update editing_pool table if it is used.
		// 3. Update log table
		if(!session.isNew())
		{
			String sid = (String) session.getAttribute("sid");
			String username = (String) session.getAttribute("username");
			String sessionid = session.getId();
			this.clearSession(session);
			
			// Need to clean db too
			DBSession dbsession = new DBSession();
			dbsession.setConfFile(ServletContext + GlobalConstant.configFilePath);			
			DBEditingpool dbeditingpool = new DBEditingpool();
			dbeditingpool.setConfFile(ServletContext + GlobalConstant.configFilePath);			
			try
			{
				dbsession.deleteSession(sid, sessionid, username);
				dbeditingpool.deleteRecord(username, sessionid);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
			if(username.compareTo(GlobalConstant.userAnonymous)!=0)
			{				
				//response.sendRedirect(GlobalConstant.JSPLogin);
				request.setAttribute(GlobalConstant.responseType,GlobalConstant.typeSuccess);
				request.setAttribute(GlobalConstant.responseControl,  GlobalConstant.cmdLogout);
				request.setAttribute(GlobalConstant.responseMsg, "You have logout successfully!");
			}
		}
		
		System.out.println("[LOGOUTMANAGER] Forward to "+GlobalConstant.JSPLogin);
		RequestDispatcher rd = request.getRequestDispatcher(GlobalConstant.JSPLogin+"?"+querystring);
		rd.forward(request, response);			
	}	
	public static void clearSession(HttpSession session)
	{
		// Clean all of the session attributes			
		
		Enumeration sessionKeys = session.getAttributeNames();
		while (sessionKeys.hasMoreElements())
		{
			String sessionKey = (String) sessionKeys.nextElement();
			session.removeAttribute(sessionKey);			
		}
		
		//Set to anonymous user
		session.setAttribute(GlobalConstant.username, GlobalConstant.userAnonymous);
		session.setAttribute(GlobalConstant.sid, "0"); 
	}
}
